package com.meessiom.train.crm.customer.controller;

import com.meessiom.train.crm.customer.model.Customer;
import com.meessiom.train.crm.customer.repository.CustomerRepository;
import com.meessiom.train.crm.customer.service.CustomerService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin({"*"})
@RestController
@RequestMapping({"/api/v1/customers"})
public class CustomerController {
    @Autowired
    private CustomerService customerService;
    @Autowired
    private CustomerRepository customerRepository;

    public CustomerController() {
    }

    @GetMapping
    public List<Customer> getAllCustomers() {
        return this.customerService.getAllCustomers();
    }

    @PostMapping
    public Customer createCustomer(@RequestBody Customer customer) {
        return this.customerService.createCustomer(customer);
    }

    @GetMapping({"{id}"})
    public ResponseEntity<Customer> getCustomerById(@PathVariable long id) {
        Customer customer = this.customerService.getCustomerById(id);
        return ResponseEntity.ok(customer);
    }

    @GetMapping({"/findByNameAndPhoneAndAddress/"})
    public List<Customer> findCustomerByNameLikeAndPhoneLikeAndAddressLike(@RequestParam("name") String name, @RequestParam("phone") String phone, @RequestParam("address") String address) {
        return this.customerRepository.findCustomerByCustomerNameLikeAndCustomerPhoneLikeAndCustomerAddressLike("%" + name + "%", "%" + phone + "%", "%" + address + "%");
    }

    @GetMapping({"/getCustomerNameById/{id}"})
    public String getCustomerNameByCustomerId(@PathVariable long id) {
        String customerName = this.customerService.getCustomerNameByCustomerId(id);
        return customerName;
    }

    @PutMapping({"{id}"})
    public ResponseEntity<Customer> deleteCustomer(@PathVariable long id, @RequestBody Customer customerDetails) {
        Customer updateCustomer = this.customerService.updateCustomer(id, customerDetails);
        return ResponseEntity.ok(updateCustomer);
    }

    @DeleteMapping({"{id}"})
    public ResponseEntity<HttpStatus> deleteCustomer(@PathVariable long id) {
        this.customerService.deleteCustomer(id);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }
}
